package com.xuerhua.yxt.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.xuerhua.yxt.model.VisitorAppointment;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.MenuConst;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.model.Grid;
import com.xuerhua.yxt.page.OrderBy;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.VisitorAppointmentQueryVO;
import com.xuerhua.yxt.reqVo.VisitorAppointmentReqVO;
import com.xuerhua.yxt.service.IParentService;
import com.xuerhua.yxt.service.IVisitorAppointmentService;
import com.xuerhua.yxt.utils.DateUtil;
import com.xuerhua.yxt.utils.HkFaceUtil;
import com.xuerhua.yxt.view.ParentPersonImportView;
import com.xuerhua.yxt.view.VisitorAppointmentView;

@Controller
public class VisitorAppointmentController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(VisitorAppointmentController.class);
	
	private final static String STUDENT_URL = Const.STUDENT_ROLE + MenuConst.VISITOR_APPOINTMENT;
	private final static String TEACHER_URL = Const.TEACHER_ROLE + MenuConst.VISITOR_APPOINTMENT;
	
	@Autowired
	private IVisitorAppointmentService visitorAppointmentService;
	@Autowired
	private IParentService parentService;
	
	@RequestMapping(STUDENT_URL + "/myApply")
	public String myApply() {
		return "visitorAppointment/myApply";
	}
	
	@RequestMapping(STUDENT_URL + "/apply")
	public String apply() {
		return "visitorAppointment/apply";
	}
	
	@RequestMapping(TEACHER_URL)
	public String applyList() {
		return "visitorAppointment/applyList";
	}
	
	@RequestMapping(TEACHER_URL + "/detail")
	public String teacherDetail(VisitorAppointment va, Model model) {
		VisitorAppointmentView detail = visitorAppointmentService.selectViewById(va);
		model.addAttribute("detail", detail);
		return "visitorAppointment/detail";
	}

	//TODO 待修改对应页面的url参数，把 detail/{{id}} 改为 detail?id={{id}}
	@RequestMapping(STUDENT_URL + "/detail}")
	public String studentDetail(VisitorAppointment va, Model model) {
		VisitorAppointmentView detail = visitorAppointmentService.selectViewById(va);
		model.addAttribute("detail", detail);
		return "visitorAppointment/detail";
	}
	
	@RequestMapping(STUDENT_URL + "/visited")
	public String visited(Model model) {
		VisitorAppointmentView detail = visitorAppointmentService.selectCurrentVisited(
				getAppUser().getParent().getRelId());
		if(detail == null) {
			VisitorAppointmentReqVO record = new VisitorAppointmentReqVO();
			Date currDate = new Date();
			record.setVisitStartTime(currDate);
			record.setVisitEndTime(DateUtil.addHours(currDate, 2));
			record.setVisitPurpose("家长授权访客");
			record.setVisitorName(getAppUser().getParent().getStudentName() + "的家长");
			record.setGender(1);
			String phone = getAppUser().getParent().getPhone();
			record.setPhoneNo(StringUtils.isBlank(phone) ? "15815667980" : phone);
			ParentPersonImportView parentView = parentService.selectParentViewByStudent(
					getAppUser().getParent().getId(), 
					getAppUser().getParent().getStudentId());
			if(StringUtils.isBlank(parentView.getFaceGroupCode())) {
				model.addAttribute("error", "请先进行人脸采集");
			}else if(StringUtils.isBlank(parentView.getFacePersonId())) {
				model.addAttribute("error", "暂时无法进行访客申请，需等信息同步");
			}else {
				record.setParentRelId(getAppUser().getParent().getRelId());
				record.setReceptionistId(parentView.getFacePersonId());
				String result = HkFaceUtil.VisitorAppointment(record);
				JSONObject object = JSONObject.parseObject(result);
				if("0".equals(object.getString("code"))) {
					JSONObject dataObject = object.getJSONObject("data");
					record.setAppointRecordId(dataObject.getString("appointRecordId"));
		    		JSONArray array = dataObject.getJSONArray("appointmentInfoList");
		    		JSONObject json = array.getJSONObject(0);
		    		record.setVerificationCode(json.getString("verificationCode"));
		    		record.setQrCode(json.getString("QRCode"));
		    		visitorAppointmentService.insertSelective(record);
		    		model.addAttribute("detail", record);
				}else {
					model.addAttribute("error", object.getString("msg"));
				}
			}
		}else {
			model.addAttribute("detail", detail);
		}
		return "visitorAppointment/visited";
	}
	
	
	
	@RequestMapping(STUDENT_URL + "/apply/submit")
	@ResponseBody Object applySubmit(VisitorAppointmentReqVO record) {
		try {
			record.setVisitStartTime(DateUtil.strToDate(record.getVisitStartDate(), 
					DateUtil.DEFAULT_DATE_FORMAT1));
			record.setVisitEndTime(DateUtil.strToDate(record.getVisitEndDate(), 
					DateUtil.DEFAULT_DATE_FORMAT1));
			ParentPersonImportView parentView = parentService.selectParentViewByStudent(
					getAppUser().getParent().getId(), 
					getAppUser().getParent().getStudentId());
			if(StringUtils.isBlank(parentView.getFaceGroupCode())) {
				return new RspResult(Status.FAIL.getCode(), "请先进行人脸采集");
			}
			if(StringUtils.isBlank(parentView.getFacePersonId())) {
				return new RspResult(Status.FAIL.getCode(), "暂时无法进行访客申请，需等信息同步");
			}
			record.setParentRelId(getAppUser().getParent().getRelId());
			record.setReceptionistId(parentView.getFacePersonId());
			String result = HkFaceUtil.VisitorAppointment(record);
			JSONObject object = JSONObject.parseObject(result);
			if("0".equals(object.getString("code"))) {
				JSONObject dataObject = object.getJSONObject("data");
				record.setAppointRecordId(dataObject.getString("appointRecordId"));
	    		JSONArray array = dataObject.getJSONArray("appointmentInfoList");
	    		JSONObject json = array.getJSONObject(0);
	    		record.setVerificationCode(json.getString("verificationCode"));
	    		record.setQrCode(json.getString("QRCode"));
	    		visitorAppointmentService.insertSelective(record);
				return new RspResult(Status.SUCCESS);
			}
			return new RspResult(Status.FAIL.getCode(), object.getString("msg"));
		} catch (Exception e) {
			logger.error("---applySubmit error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping(STUDENT_URL + "/page/query")
	@ResponseBody Object studnetPage(VisitorAppointmentQueryVO queryVO) {
		try {
			queryVO.setParentId(getAppUser().getParent().getId());
			return getGrid(queryVO);
		} catch (Exception e) {
			logger.error("---studnetPage error={}", e);
		}
		return null;
	}
	
	@RequestMapping(TEACHER_URL + "/page/query")
	@ResponseBody Object teacherPage(VisitorAppointmentQueryVO queryVO) {
		try {
			return getGrid(queryVO);
		} catch (Exception e) {
			logger.error("---teacherPage error={}", e);
		}
		return null;
	}
	
	private Grid getGrid(VisitorAppointmentQueryVO queryVO) {
		Page<VisitorAppointmentView> page = new Page<>();
		Grid grid = new Grid();
		List<OrderBy> sorts = new ArrayList<>();
		sorts.add(new OrderBy("CREATE_TIME", "desc"));
		page.setSorts(sorts);
		page.setParams(queryVO);
		page.setPageNo(queryVO.getPage());
		page.setPageSize(Integer.MAX_VALUE - 1);
		List<VisitorAppointmentView> list = visitorAppointmentService.selectListByPage(page);
		grid.setRows(list);
		grid.setTotal(page.getTotalRecord());
		return grid;
	}
	
}
